package com.ziven.common.widget.value;

import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;

import com.ziven.easygo.util.LogHelper;
import com.ziven.easygo.util.ViewHelper;

/**
 * @author Ziven
 */
public class RuleValue extends Value {

    private static final String TAG = "RuleValue";

    public static RuleValue rule(int rule) {
        return new RuleValue(rule);
    }

    public static RuleValue rule(int rule, int subject) {
        return new RuleValue(rule, subject);
    }

    private RuleValue(int rule) {
        value = rule;
    }

    private RuleValue(int rule, int subject) {
        value = rule;
        id = subject;
    }

    @Override
    protected void takeEffect(@NonNull ViewHelper<? extends View> helper) {
        if(!(value instanceof Integer)) {
            return;
        }
        int rule = (int) value;
        int subject = id instanceof Integer ? (int) id : RelativeLayout.TRUE;
        LogHelper.log(TAG, "rule=" + rule + " subject=" + subject);
        helper.getViewNulls().doNotNull(view -> {
            RelativeLayout.LayoutParams layoutParams;
            ViewGroup.LayoutParams params = view.getLayoutParams();
            if(params instanceof RelativeLayout.LayoutParams) {
                layoutParams = (RelativeLayout.LayoutParams) params;
            } else if(params instanceof ViewGroup.MarginLayoutParams) {
                layoutParams = new RelativeLayout.LayoutParams((ViewGroup.MarginLayoutParams) params);
            } else if(params != null) {
                layoutParams = new RelativeLayout.LayoutParams(params);
            } else {
                layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            }
            layoutParams.addRule(rule, subject);
            view.setLayoutParams(layoutParams);
        });
    }
}
